package com.xxxx.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.xxxx.seckill.exception.GlobalException;
import com.xxxx.seckill.mapper.OrderMapper;
import com.xxxx.seckill.pojo.Order;
import com.xxxx.seckill.pojo.SeckillGoods;
import com.xxxx.seckill.pojo.SeckillOrder;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IGoodsService;
import com.xxxx.seckill.service.IOrderService;
import com.xxxx.seckill.service.ISeckillGoodsService;
import com.xxxx.seckill.service.ISeckillOrderService;
import com.xxxx.seckill.utils.MD5Util;
import com.xxxx.seckill.utils.UUIDUtil;
import com.xxxx.seckill.vo.GoodsVo;
import com.xxxx.seckill.vo.OrderDetailVo;
import com.xxxx.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author heyanfeng
 * @since 2022-08-01
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * @Author heyanfeng
     * @Description
     * 功能描述:     库存消减
     * @Date 11:03 2022/8/31
     * @Param [user, goods]
     * @return com.xxxx.seckill.pojo.Order
     **/
    @Override
    @Transactional
    public Order seckill(User user, GoodsVo goods) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //秒杀商品表减库存
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>()
                .eq("goods_id",goods.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount()-1);
        //库存超卖问题
        //v1 会有订单多出的问题
//        seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
//                .set("stock_count",seckillGoods.getStockCount())//更新库存
//                .eq("id",seckillGoods.getId()) //条件id
//                .gt("stock_count",0)); //附加条条件
        /**
         * @Description
         * 问题描述：库存超卖问题
         * 原理: update行级的排他锁，原子性操作，可保证线程安全
         * 库存超卖，订单库存不统一问题：
         * 1、扣库存这里利用sql语句处理，且加了库存数量的限制必须大于0
         * 2、在秒杀订单表中加唯一索引（用户id+商品id的唯一索引，解决同一个用户秒杀多商品的问题）
         * 3、优化重复抢购直接进Redis处理
        */
        boolean result = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
                .setSql("stock_count = stock_count -1")
                .eq("goods_id", goods.getId())
                .gt("stock_count", 0));

        if(seckillGoods.getStockCount()<1){
            //判断是否还有库存
            valueOperations.set("isStockEmpty:"+goods.getId(),"0");
            return null;
        }

        //创建订单--- 插入操作自动返回主键
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        order.setPayDate(new Date());
        orderMapper.insert(order);

        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrderService.save(seckillOrder);
        redisTemplate.opsForValue().set("order:"+user.getId()+":" +goods.getId(),seckillOrder);
        return order;
    }

   /**
    * @Author heyanfeng
    * @Description 
    * 功能描述:订单详情
    * @Date 11:16 2022/8/26
    * @Param [orderId]
    * @return com.xxxx.seckill.vo.OrderDetailVo
    **/
    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId==null){
        throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
    }
        Order order = orderMapper.selectById(orderId);
        GoodsVo goodsVO = goodsService.findGoodsVOByGoodsId(order.getGoodsId());
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setGoodsVo(goodsVO);
        orderDetailVo.setOrder(order);
        return orderDetailVo;
    }

    /**
     * @Author heyanfeng
     * @Description
     * 功能描述:    获取秒杀地址
     * @Date 12:43 2022/9/1
     * @Param [user, goodsId]
     * @return java.lang.String
     **/
    @Override
    public String createPath(User user, Long goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisTemplate.opsForValue().set("seckillPath"+ user.getId()+":"+goodsId,str,60, TimeUnit.SECONDS);
        return str;
    }

    /**
     * @Author heyanfeng
     * @Description
     * 功能描述:    校验秒杀地址
     * @Date 15:12 2022/9/1
     * @Param [user, goodsId, path]
     * @return boolean
     **/
    @Override
    public boolean checkPath(User user, Long goodsId,String path) {
        if (user ==null||goodsId<0|| StringUtils.isEmpty(path)){
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }

    /**
     * @Author heyanfeng
     * @Description
     * 功能描述:    校验验证码
     * @Date 16:06 2022/9/1
     * @Param [user, goodsId, captcha]
     * @return boolean
     **/
    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(captcha)) {
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }
}
